package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;


    /**
     * 新增班级
     * @param clazz
     */
    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(clazz.getCreateTime());
        clazzMapper.insert(clazz);
    }

    /**
     * 查询所有班级
     * @return
     */
    @Override
    public List<Clazz> selectAll() {
        return clazzMapper.selectAll();
    }
    /**
     * 班级列表查询
     * 根据班级列表数据的条件分页查询
     */
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        //1.设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        Page<Clazz> pageInfo = clazzMapper.list(clazzQueryParam);
        List<Clazz> list = pageInfo.getResult();
        //遍历list，计算班级状态
        for (Clazz clazz : list) {
            calculateAndSetStatus(clazz);
        }
        return new PageResult<>(pageInfo.getTotal(),list);
    }
    /**
     * 删除班级
     * @param id
     */
    @Override
    public void deleteClazz(Integer id) {
        clazzMapper.deleteClazz(id);
    }
    /**
     * 根据id查询班级
     * @param id
     */
    @Override
    public Clazz selectById(Integer id) {
        Clazz clazz = clazzMapper.selectById(id);
        return clazz;
    }
    /**
     * 修改班级
     * @param clazz
     */
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }
    /**
     * 私有方法，用于计算班级状态
     * @param clazz 班级对象
     */
    private void calculateAndSetStatus(Clazz clazz) {
        LocalDate nowDate = LocalDate.now();
        LocalDate beginDate = clazz.getBeginDate();
        LocalDate endDate = clazz.getEndDate();

        String status;
        if (nowDate.isBefore(beginDate)) {
            status = "未开班";
        } else if (nowDate.isAfter(endDate)) {
            status = "已结课";
        } else {
            status = "在读";
        }
        clazz.setStatus(status);
    }
}
